package com.zhq.controller;

import com.zhq.bean.Courier;
import com.zhq.bean.Message;
import com.zhq.mvc.ResponseBody;
import com.zhq.service.AdminService;
import com.zhq.service.CourierService;
import com.zhq.util.JSONUtil;
import com.zhq.util.UserUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @Author:钟豪强
 * @Description:    处理管理员登录请求
 * @Date Created in  2020-08-14 14:42
 * @Modified By:
 */
public class AdminController {

    @ResponseBody("/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){
        System.out.println("接收到请求");
        //1.接收参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("username="+username+",password="+password);
        //2.调用service方法,传入参数,获取结果
        boolean result = AdminService.login(username, password);
        boolean login = CourierService.login(username, password);
        //3.根据结果,返回不同的数据给ajax
        Message msg = null;
        if (result) {
            msg = new Message(0,"登录成功");//{status:0,result:"登录成功"}
            //更新登录时间和登录ip
            Date date = new Date();
            String ip = request.getRemoteAddr();
            AdminService.updateLoginTime(username,date,ip);
            request.getSession().setAttribute("adminUserName",username);
        }else if(login){
            //快递员
            msg = new Message(0,"登录成功");//{status:0,result:"登录成功"}
            request.getSession().setAttribute("adminUserName",username);
        }else {
            msg = new Message(-1,"登录失败");//{status:-1,result:"登录失败"}
        }
        //4.转换成JSON格式
        String json = JSONUtil.toJSON(msg);
        return json;
    }

    @ResponseBody("/admin/isCourier.do")
    public String confirm(HttpServletRequest request, HttpServletResponse response){
        String userName = UserUtil.getUserName(request.getSession());
        System.out.println(userName);
        Courier courier = CourierService.findByUserName(userName);
        System.out.println(courier);
        boolean flag = AdminService.find(userName);
        System.out.println(flag);
        courier.setAdmin(flag);
        Message msg = new Message();
        if (courier != null) {
            String userPhone = courier.getUserPhone();
            request.getSession().setAttribute("adminUserPhone", userPhone);
            msg.setData(courier);
            msg.setStatus(0);
        }else{
            msg.setStatus(-1);
        }
        return JSONUtil.toJSON(msg);
    }
}
